package com.example.esp8266.Login;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import android.content.SharedPreferences;
import android.content.Context;

import com.example.esp8266.Library.Sql.SqlServer;
import com.example.esp8266.Main.MainActivity;
import com.example.esp8266.R;
import com.example.esp8266.Init.SplashActivity;

import java.sql.SQLException;
import java.util.Objects;

public class SigninActivity extends AppCompatActivity {

    String select_result = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //登录初始化
        // 获取 SharedPreferences 对象，如果文件已存在则不创建新文件
        SharedPreferences sharedPref = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

        // 获取参数值
        String user_name = sharedPref.getString("user_name", "  用户名");

        EditText user_name_tx = findViewById(R.id.login_name);
        user_name_tx.setText(user_name);

        user_name_tx.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 判断输入框原本的文字是否为空
                if (s.length() > 0) {
                    // 清除输入框原本的文字
                    user_name_tx.setText("");
                    // 移除 TextWatcher，确保只执行一次
                    user_name_tx.removeTextChangedListener(this);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
                //
            }
        });

        EditText edit_password_Text = findViewById(R.id.login_password);
        edit_password_Text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 判断输入框原本的文字是否为空
                if (s.length() > 0) {
                    // 清除输入框原本的文字
                    edit_password_Text.setText("");
                    // 移除 TextWatcher，确保只执行一次
                    edit_password_Text.removeTextChangedListener(this);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
                //
            }
        });
    }

    public void login_btn_down(View view) {
        String TAG = "SQL_Service";

        EditText user_name_input = findViewById(R.id.login_name);
        EditText password_input = findViewById(R.id.login_password);
        String user_name_input_result = user_name_input.getText().toString();
        String password_input_result = password_input.getText().toString();

        if (user_name_input_result.isEmpty() || password_input_result.isEmpty()) {
            Toast.makeText(SigninActivity.this, "登录失败，用户名或密码为空", Toast.LENGTH_LONG).show();
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                SqlServer sql = new SqlServer("test", "Abc123456", "SunXiaoCheng", "117.10.124.2");
                sql.connect();

                if (!sql.isConnected()) {
                    Log.e(TAG, "Failed to connect to SQL server.");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SigninActivity.this, "Network error: failed to connect to SQL server", Toast.LENGTH_LONG).show();
                            SharedPreferences sharedPref = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPref.edit();
                            editor.putBoolean("login_state_error", true); // 登录异常的状态参数为 true
                            editor.apply();
                            finish();
                            startActivity(new Intent(SigninActivity.this, SplashActivity.class));
                        }
                    });
                    return;
                }

                try {
                    select_result = sql.Select("select password from [TEST] where user_name='" + user_name_input_result + "'", "password");
                } catch (SQLException e) {
                    Log.e(TAG, "Sign: Search SQL server failed: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SigninActivity.this, "Network error: failed to query SQL server", Toast.LENGTH_LONG).show();
                            SharedPreferences sharedPref = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPref.edit();
                            editor.putBoolean("login_state_error", true); // 登录异常的状态参数为 true
                            editor.apply();
                            finish();
                            startActivity(new Intent(SigninActivity.this, SplashActivity.class));
                        }
                    });
                    return;
                }

                // 查询完成后，比对密码
                runOnUiThread(new Runnable() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void run() {
                        Log.i(TAG, select_result.trim() + "s" + password_input_result); // 测试
                        if (Objects.equals(select_result.trim(), password_input_result.trim())) {
                            SharedPreferences sharedPref = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPref.edit();
                            editor.putString("user_name", user_name_input_result);
                            editor.putBoolean("login_state", true); // 登录状态参数为 true
                            editor.apply();
                            finish();
                            startActivity(new Intent(SigninActivity.this, SplashActivity.class));
                        } else {
                            Toast.makeText(SigninActivity.this, "登录失败，请检查用户名和密码", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        }).start();
    }

}

